<template>
  <!-- 驾驶员-下拉框查询 -->
  <div>
    <a-select v-bind="$attrs" v-on="$listeners" :placeholder="placeholder" v-model="currentValue"
              allowClear>
      <a-icon v-if="fetching" style="color: #096dd9" slot="suffixIcon" type="loading" />
      <a-spin v-if="fetching" slot="notFoundContent" size="small" />

      <a-select-option v-for="i in filterList" :key="i[valueName]" :value="i[[valueName]]">
        <span :title="getLabel(i)">
          <span> {{ getLabel(i) }}</span>
        </span>
      </a-select-option>
    </a-select>
  </div>
</template>
<script>
import { carDriverInfo } from '@/api/office/vehicle/config' // api

export default {
  name: 'SelectDriver',
  data() {
    return {
      fetching: false,
      list: [],
    }
  },
  props: {
    // v-model绑定的数据
    value: {
      type: [Array, String, Object, Number],
    },
    attr: {
      type: [Object],
    },
    // placeholder
    placeholder: {
      type: String,
      default: function () {
        return '请选择驾驶员'
      },
    },
    // value值名
    valueName: {
      type: String,
      default: function () {
        return 'driverId'
      },
    },
  },
  computed: {
    // 筛选列表
    filterList() {
      return this.list?.filter((item) => item.isCheck === '0' || (item.driverId && item.driverId === this.currentValue)) || []
    },
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function () {
        let _val = null;
        if (this.list.length > 0) {
          let _obj = this.list.find((item) => item[this.valueName] === this.value)
          this.$emit(
            'update:option',
            _obj
          )
          this.$emit(
            'getOption',
            _obj
          )
          _val = this.value
        } else {
          //无下拉数据的情况下设置自定义label值
          _val = this.attr.driverName ? this.attr.driverName : null;
        }
        return _val
      },
      set: function (value) {
        this.$emit('input', value)
      },
    },
  },
  watch: {
    attr: {
      deep: true,
      handler(e) {
        if (Object.keys(e)?.length > 0) {
          this.getList()
        }
      },
    }
  },
  methods: {
    getLabel(curRow) {
      let _str = curRow.driverName
      if (curRow.phone) {
        _str += `（${curRow.phone}）`
      }
      return _str;
    },
    getList() {
      // 获取下拉框列表
      this.fetching = true
      let args = {}
      if (this.attr && Object.keys(this.attr)?.length > 0) {
        Object.assign(args, this.attr)
      }
      carDriverInfo
        .getAllList(args)
        .then((res) => {
          this.fetching = false
          const dataList = res.data || []
          this.list = dataList
          console.log(this.list, "===35353535")
          this.$emit('update:list', this.list)
          this.$emit('getList', this.list)
        })
        .catch(() => {
          this.fetching = true
        })
    },
  },
}
</script>
